// const BASE_URL = "http://116.204.108.230:8090"
const BASE_URL = "http://localhost:8090"
// 定义默认参数
const defaultOptions = {
  data: {},
  ignoreToken: false,
  form: false,
}
/**
 * 发送请求
 * @params
 * method: <String> 请求方式: POST/GET
 * url: <String> 请求路径
 * data: <Object> 请求参数
 * ignoreToken: <Boolean> 是否忽略token验证
 * form: <Boolean> 是否使用formData请求
 */
function request(options) {
  let _options = Object.assign(defaultOptions, options)
  let {
    method,
    url,
    data,
    ignoreToken,
    form
  } = _options
  const app = getApp()
  // 设置请求头
  let header = {}
  if (form) {
    header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
  } else {
    header = {
      'content-type': 'application/json' //自定义请求头信息
    }
  }
  if (!ignoreToken) {
    // 从全局变量中获取token
    let token = wx.getStorageSync('token')
    if (token !== "") {
      header.Authentication = token
    }
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + url,
      data,
      header,
      method,
      success: (response) => {
        resolve(response)
      },
      fail: (err) => {
        showToast(err.errMsg)
        reject(err)
      }
    })
  })
}

// 封装toast函数
function showToast(title, icon = 'none', duration = 3000, mask = false) {
  wx.showToast({
    title: title || '',
    icon,
    duration,
    mask
  });
}

function get(options) {
  return request({
    method: 'GET',
    ...options
  })
}

function post(options) {
  // url, data = {}, ignoreToken, form
  return request({
    method: 'POST',
    ...options
  })
}

function put(options) {
  // url, data = {}, ignoreToken, form
  return request({
    method: 'PUT',
    ...options
  })
}
function del(options) {
  // url, data = {}, ignoreToken, form
  return request({
    method: 'DELETE',
    ...options
  })
}

module.exports = {
  request,
  get,
  post,
  put,
  del,
}
